package com.lame.sbconstant.product.strategy;

import com.lame.detect.vo.ClassMeta;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class TplTools {

    public static String generate(ClassMeta classMeta, String tpl) {
        Map<String, Object> root = new HashMap<>(5);
        root.put("ENTITY", classMeta.getName());

        root.put("fields", classMeta.getFields());
        String pkg = StringUtils.substringBeforeLast(classMeta.getPackageName(), ".");
        root.put("PACKAGE", pkg);
        root.put("BASE_PKG", StringUtils.substringAfter(pkg, "package "));
        Configuration configuration = new Configuration();
        StringWriter stringWriter = new StringWriter();
        try {
            Template template = new Template(classMeta.getName(), tpl, configuration);
            template.process(root, stringWriter);
            System.out.println(stringWriter.toString());
            return stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
